#!/usr/bin/env bash
# Copyright (c) 2021 maminjie <maminjie2@huawei.com>
# SPDX-License-Identifier: MulanPSL-2.0

method_def rpmdiff


usage_rpmdiff() {
printf "rpmdiff: Check the difference of RPM package

usage:
    ${PROG} rpmdiff dir1 dir2
    ${PROG} rpmdiff rpm1 rpm2

"
}

# rpm_name rpmpkg
rpm_name() {
    [[ -n "$1" ]] && rpm -qi $1 2>/dev/null | grep "Name" | head -n1 | awk '{print $3}'
}

# __do_rpmdiff dir1 dir2
__do_rpmdiff() {
    local src_rpms=$(ls $1/*.rpm 2> /dev/null)
    local dst_rpms=$(ls $2/*.rpm 2> /dev/null)
    declare -A src_dict
    declare -A dst_dict

    for r in $src_rpms; do
        local name=$(rpm_name "$r")
        if [ -n "$name" ]; then
            dict_add src_dict "$name" "$r"
        fi
    done
    for r in $dst_rpms; do
        local name=$(rpm_name "$r")
        if [ -n "$name" ]; then
            dict_add dst_dict "$name" "$r"
        fi
    done

    local src_keys=$(dict_keys src_dict)
    local i=1
    local dcnt=0
    for k in $src_keys; do
        local srpm=$(dict_get src_dict "$k")
        local drpm=$(dict_get dst_dict "$k")
        if [ -z "$drpm" ]; then
            echo "$i) -only $srpm"
            ((dcnt++))
        else
            local res=$(rpmdiff "$srpm" "$drpm")
            if [ -z "$res" ]; then
                echo "$i) equal $srpm $drpm"
            else
                local resdiff=$(echo "$res" | grep -vE "\.{10}T")
                if [ -z "$resdiff" ]; then
                    echo "$i) equal $srpm $drpm"
                else
                    resdiff=$(echo "$res" | grep -E "^(added|removed)")
                    if [ -n "$resdiff" ]; then
                        echo "$i) diff $srpm $drpm"
                    else
                        echo "$i) ~diff $srpm $drpm"
                    fi
                    ((dcnt++))
                fi
                echo "$res"
            fi
            dict_remove dst_dict "$k"
        fi
        ((i++))
    done
    local dst_values=$(dict_values dst_dict)
    for v in $dst_values; do
        echo "$i) +only $v"
        ((dcnt++))
        ((i++))
    done
    echo ""
    echo "There are about $dcnt differences..."
}

# do_rpmdiff dir1 dir2
# do_rpmdiff rpm1 rpm2
do_rpmdiff() {
    if [ $# -ne 2 ]; then
        usage_rpmdiff; exit
    fi
    local a1="$1"
    local a2="$2"
    if [[ -f "$a1" && -f "$a2" ]]; then
        rpmdiff "$a1" "$a2"
    elif [[ -d "$a1" && -d "$a2" ]]; then
        __do_rpmdiff "$a1" "$a2"
    else
        usage_rpmdiff
    fi
}

rpm_docheck() {
    check_command "rpm"
    check_command "rpmdiff"
}
